from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import uuid
from django.urls import reverse
from datetime import date

# Create your models here.

class Genre(models.Model):
    name = models.CharField(max_length=200, help_text='输入图书类型 (例如: 科幻, 历史)')

    def __str__(self):
        return self.name

class Language(models.Model):
    name = models.CharField(max_length=200, help_text='输入图书语言 (例如: 中文, 英文)')

    def __str__(self):
        return self.name

class Author(models.Model):
    objects = None
    name = models.CharField(max_length=100, verbose_name='姓名')
    date_of_birth = models.DateField(null=True, blank=True)
    date_of_death = models.DateField('逝世日期', null=True, blank=True)
    bio = models.TextField(max_length=1000, help_text='作者简介', blank=True, verbose_name='简介')

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('author-detail', args=[str(self.id)])

class Book(models.Model):
    title = models.CharField(max_length=200, verbose_name='书名')
    author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True, verbose_name='作者')
    summary = models.TextField(max_length=1000, help_text='请输入本书简介', verbose_name='简介')
    isbn = models.CharField('ISBN', max_length=13, unique=True,
                          help_text='13位 <a href="https://www.isbn-international.org/content/what-isbn">ISBN</a> 号码')
    genre = models.ManyToManyField(Genre, help_text='选择图书类型')
    language = models.ForeignKey(Language, on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('book-detail', args=[str(self.id)])

    def display_genre(self):
        return ', '.join(genre.name for genre in self.genre.all()[:3])
    display_genre.short_description = '类型'

class BookInstance(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='唯一ID')
    book = models.ForeignKey('Book', on_delete=models.RESTRICT, verbose_name='图书')
    imprint = models.CharField(max_length=200, verbose_name='版本信息')
    due_back = models.DateField(null=True, blank=True, verbose_name='归还日期')
    borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='借阅者')

    LOAN_STATUS = (
        ('m', '维护中'),
        ('o', '已借出'),
        ('a', '可用'),
        ('r', '已预订'),
    )
    status = models.CharField(
        max_length=1,
        choices=LOAN_STATUS,
        blank=True,
        default='m',
        help_text='图书状态',
    )

    class Meta:
        ordering = ['due_back']
        permissions = (("can_mark_returned", "设置图书为已归还"),)

    def __str__(self):
        return f'{self.id} ({self.book.title})'

    def renew(self, new_due_back):
        """续借图书，更新归还日期"""
        self.due_back = new_due_back
        self.save()

    @property
    def is_overdue(self):
        if self.due_back and date.today() > self.due_back:
            return True
        return False
